package org.glut.cloud.serviceRating.common;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author weisiyuan
 * @createtime 2024/8/19 9:41
 */
@Component
@Aspect // 切面 定义了通知和切点的关系
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(org.glut.cloud.serviceRating.common.LogAnnotation)")
    public void pt() {}

    //  环绕通知
    @Around("pt()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long BeginTime = System.currentTimeMillis();
        // 执行方法
        Object result = joinPoint.proceed();
        // 执行时长（毫秒）
        long time = System.currentTimeMillis() - BeginTime;
        // 保存日志
        rocordLog(joinPoint, time);
        return result;
    }
    private void rocordLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("===========================log start================================");
        log.info("module:{}", logAnnotation.module());
        log.info("operation:{}", logAnnotation.operation());

        // 请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("request method:{}", className + "." + methodName + "()");

        // 请求的参数
        Object[] args = joinPoint.getArgs();
        String params = JSON.toJSONString(args[0]);
        log.info("params:{}", params);

        // 获取request 设置IP地址
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        log.info("ip:{}", IpUtil.getIpAddr(request));

        log.info("excute time : {} ms", time);
        log.info("===========================log end================================");
    }
}
